#include "ProceduralTerrainTool.h"

ProceduralTerrainTool::ProceduralTerrainTool()
:rend(RenderManager::getInstance())
{
}

ProceduralTerrainTool* ProceduralTerrainTool::getInstance()
{
    static ProceduralTerrainTool* inst=0;
    if(!inst)return inst=new ProceduralTerrainTool();
    else return inst;
}


void ProceduralTerrainTool::tester()
{

    printf("[%f]",EqnParser("x").eval(10,20,2));
    printf("[%f]",EqnParser("y").eval(100,2,2));
}

void ProceduralTerrainTool::genTerrain(const char *surfEqn,
                                       const char *redEqn,
                                       const char *greenEqn,
                                       const char *blueEqn
                                       ,const vector3<int> &start
                                       , const vector3<int> &end){

    EqnParser surface(surfEqn), red(redEqn), blue(blueEqn),green(greenEqn);
    voxel v;
    for(int i=start.x+1;i<end.x;i++)
        for(int j=start.z+1;j<end.z;j++)
        {

                int k=surface.eval(i,0,j);
                int l,diff;
                float iter;
                l=surface.eval(i-1,0,j);
                diff=k-l;
                iter=abs(diff)*SAMPLING_RATE+1;
                for(int s=0;s<=iter;s++)
                {
                    int t=l+diff*(s/iter);
                    if(t<end.x && t>=0)
                    {
                    v.setColor(fmod(red.eval(i-1,t,j),256),
                               fmod(blue.eval(i-1,t,j),256),
                               fmod(green.eval(i-1,t,j),256));
                    rend->addVoxel(i-1,t+0.5,j,v);
                    }
                }

                l=surface.eval(i,0,j-1);
                diff=k-l;
                iter=abs(diff)*SAMPLING_RATE+1;
                for(int s=0;s<=iter;s++)
                {
                    int t=l+diff*(s/iter);
                    if(t<end.x && t>=0)
                    {
                    v.setColor(fmod(red.eval(i,t,j-1),256),
                               fmod(blue.eval(i,t,j-1),256),
                               fmod(green.eval(i,t,j-1),256));
                    rend->addVoxel(i,t,j-1+0.5,v);
                    }
                }
        }

}
